import { javascript } from "@codemirror/lang-javascript";
import { Modal } from "antd";
import CodeMirror from '@uiw/react-codemirror';
import { memo, useEffect, useState } from "react";
import encrypt from "../utils/utils";


const templateCode = (prjectId: string) => {
 
  return `const axios = require('axios');

const url = '${window.location.origin}/v1/chat/completions';
const headers = {
  'Content-Type': 'application/json',
  'Authorization': 'Bearer ${encrypt(prjectId)},3287'
};

const data = {
  stream: true,
  messages: [
    {
      role: 'system',
      content: '你是AI助手'
    },
    {
      role: 'user',
      content: '你是谁？'
    }
  ]
};

axios.post(url, data, { headers })
  .then(response => {
    const result = response.data;
    console.log(result);
  })
  .catch(error => {
    console.error(error);
  });
`
}

interface Props {
  open: boolean;
  onClose: () => void;
}

const Api = (props: Props) => {
  const { open, onClose } = props
  const [code, setCode] = useState<string>();

  useEffect(() => {
    if (open) {
      const searchParams = new URLSearchParams(window.location.search);
      const projectId = searchParams.get('projectId');
      if (projectId) setCode(templateCode(projectId))
    }
  }, [open])


  return <Modal
    title="API"
    width={760}
    open={open}
    footer={null}
    destroyOnClose={true}
    onCancel={() => onClose()}>
    <CodeMirror
      style={{ borderRadius: 10, overflow: "hidden", outline: "1px solid #E5E6ED" }}
      value={code}
      height="500px"
      editable={false}
      placeholder="请输入js代码"
      extensions={[javascript({ jsx: true })]}
    />
  </Modal>
}

export default memo(Api);